//
//  SearchViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/25.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "SearchViewController.h"
#import "GW_TextField.h"
#import "HomeSearchCell.h"
#import "LastSearchViewController.h"
#import "SearchFirstTableViewCell.h"
#import "SearchListCell.h"
#import "HomeSearchLeftCell.h"
#import "SearchRightCell.h"
#import "SearchGoodsBaseModel.h"
#import "SearchGoodsDataModel.h"
#import "SearchRightModel.h"
#import "SearchNearbyModel.h"
#import "SortModel.h"

#import "SearchModel.h" //测试  实验
@interface SearchViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *aView; //这个view的作用是使搜索的图片的占位符 调整位置
@property (nonatomic, strong) UIImageView *search; // 导航条 textfield内的搜索图标
@property (nonatomic, strong) GW_TextField *searchTextField;//自定义UITextfield目的是调整占位符位置
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *categoryBtn;//类别
@property (nonatomic, strong) UIButton *sortBtn;//排序
@property (nonatomic, strong) UIButton *nearbyBtn;//附近
@property (nonatomic, strong) UITableView *atableView;

@property (nonatomic, strong) UITableView *leftTableview;
@property (nonatomic, strong) UITableView *rightTableview;
@property (nonatomic, strong) UITableView *sortTableview;

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *aview;

@property (nonatomic, strong) NSIndexPath *indexPth;//记录当前选择的哪个cell
@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) NSMutableArray *baseArray;//店铺
@property (nonatomic, strong) NSMutableArray *dataArray;//商品
@property (nonatomic, strong) NSMutableArray *sortAtrray;//排序

@property (nonatomic, strong) NSMutableArray *leftCategoryArry;//类别的数组
@property (nonatomic, strong) NSMutableArray *rightArray;
@property (nonatomic, strong) NSMutableArray *nearbyLeft;
@property (nonatomic, strong) NSMutableArray *nearbyRight;
@property (nonatomic, strong) UITableView *nearbyLeftTableView;
@property (nonatomic, strong) UITableView *nearbyRightTableView;
@property (nonatomic, copy) NSString *key;
@property (nonatomic, copy) NSString *lon;
@property (nonatomic, copy) NSString *lat;
@property (nonatomic, copy) NSString *sortKey;
@property (nonatomic, copy) NSString *typeId;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UILabel *topLabel;

@property (nonatomic, strong) NSMutableArray *aArray;//测试
@property (nonatomic, strong) NSMutableArray *boolArray;
@property (nonatomic, strong) LoadingView *load;

@end

@implementation SearchViewController

-(NSMutableArray *)boolArray{
    if (!_boolArray) {
        _boolArray = [NSMutableArray array];
    }
    return _boolArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _indexPth = [NSIndexPath indexPathForRow:0 inSection:0];
    _aArray = [NSMutableArray arrayWithCapacity:0];
    _baseArray = [NSMutableArray arrayWithCapacity:0];
    _dataArray = [NSMutableArray arrayWithCapacity:0];
    [self setNavigation];
    
    
    _load = [[LoadingView alloc] initWithFrame:CGRectMake(0, 44 + 2, GWIDTH, GHEIGHT - 64 - 45)];
    _load.hidden = YES;
    [self.view addSubview:_load];
    
    if([GW_Request sharedInstance].noNetwork)
    {
        [_load setReminderLabelTitle:@"网络错误~!" andImage:@"search_empty"];
        
    }
    else
    {
        [_load setReminderLabelTitle:@"暂无搜索结果~!" andImage:@"search_empty"];
    }

    
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back@2x"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backItemAction)];
    
    _topLabel = [[UILabel alloc] initWithFrame:CGRectMake(98, 0, GWIDTH - 98 - 44, 30)];
    _topLabel.text = @"      可输入商品名、分类、商圈";
    _topLabel.textColor = ColorFrom16A(0x7F7E7D, 0.57);
    _topLabel.font = PFRFONT(12);
    _topLabel.layer.backgroundColor = ColorFrom16(0xf0f0f0).CGColor;
    _topLabel.layer.cornerRadius = 15;
    _topLabel.userInteractionEnabled = YES;
    self.navigationItem.titleView = _topLabel;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TextfieldAction:)];
    [_topLabel addGestureRecognizer:tap];
    _search = [[UIImageView alloc] initWithFrame:CGRectMake(5, 7.5, 15, 15)];
    _search.image = IMAGE(@"home_search_yellow");
    [_topLabel addSubview:_search];
    
    [self addLefAndRightTableview];
    
    [self startLeftTableviewNetwork];//类别的网络请求
    [self startNearbyNetwork];//附近网络请求
    [self sortNetweok];
}

- (void)backItemAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"homeChange" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sortNetweok
{
    _sortAtrray = [NSMutableArray arrayWithCapacity:0];
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/goods/GetOrderMethod", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        for (NSDictionary *dic in resultDict[@"data"]) {
            SortModel *model = [GW_Tool getObjFromDictionary:dic byClassName:@"SortModel"];
//            NSLog(@"%@", model.order_name);
            [_sortAtrray addObject:model];
        }
        [_sortTableview reloadData];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
}

- (void)startNearbyNetwork
{
    _nearbyLeft = [NSMutableArray arrayWithCapacity:0];
    _nearbyRight = [NSMutableArray arrayWithCapacity:0];
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/city/GetServeZone?city=2", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
//        NSLog(@"附近%@", resultDict);
        NSArray *array = resultDict[@"data"];
        
        for (NSDictionary *dict in array) {
            SearchNearbyModel *model = [SearchNearbyModel mj_objectWithKeyValues:dict];
            [_nearbyLeft addObject:model];
        }
        
        SearchNearbyModel *model = _nearbyLeft.firstObject;
        _nearbyRight = (NSMutableArray *) model.child_zone;
        
        [_leftTableview reloadData];
        [_rightTableview reloadData];
        
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
}

- (void)startLeftTableviewNetwork
{
    _leftCategoryArry = [NSMutableArray arrayWithCapacity:0];
    _rightArray = [NSMutableArray arrayWithCapacity:0];
    //类别 数据请求
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/store/getStoreType", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"----类别 %@", resultDict);
        NSArray *array = resultDict[@"data"];
        
        for (NSDictionary *arr in array) {
          SearchRightModel *model =  [SearchRightModel mj_objectWithKeyValues:arr];

            [_leftCategoryArry addObject:model];
        }
        SearchRightModel *model = _leftCategoryArry.firstObject;
        _rightArray = (NSMutableArray *) model.data;
        
        [_leftTableview reloadData];
        [_rightTableview reloadData];
       
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
}


//搜索商品的网络请求
- (void)startGoodsNetwork
{
    
    NSString *lat;
    NSString *lon;
    
    if([GW_Tool isEmptyString:_lat])
    {
        lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"lat"];
    }
    else
    {
        lat = _lat;
    }
    
    if([GW_Tool isEmptyString:_lon])
    {
        lon = [[NSUserDefaults standardUserDefaults] objectForKey:@"long"];
    }
    else
    {
        lon = _lon;
    }
    
    
    NSDictionary *param = @{@"key"      :STRING(_searchKey),
                            @"lat"      :STRING(lat),
                            @"lnt"      :STRING(lon),
                            @"order"    :STRING(_sortKey),
                            @"type"     :STRING(_key),
                            @"nearby"   :@"19000",
                            @"page"     :@(_page)
                            };
    
    [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/goods/getGoods", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"搜索商品 %@", resultDict);
        NSArray *arr = resultDict[@"data"];
        for (NSDictionary *dic in resultDict[@"data"]) {
//            //店铺
//            NSDictionary *dictionary = dic[@"base"];
//            SearchGoodsBaseModel *model = [GW_Tool getObjFromDictionary:dictionary byClassName:@"SearchGoodsBaseModel"];
//            [_baseArray addObject:model];
//            
//             //商品
//            for (NSDictionary *dataDict in dic[@"data"]) {
//                SearchGoodsDataModel *datamodel = [GW_Tool getObjFromDictionary:dataDict byClassName:@"SearchGoodsDataModel"];
//                [_dataArray addObject:datamodel];
//            }
            
            //新方法
            SearchModel *model22 = [SearchModel mj_objectWithKeyValues:dic];
            [_aArray addObject:model22];
            [self.boolArray addObject:@0];
        }
        
        if(self.aArray.count > 0)
        {
            _load.hidden = YES;
        }
        else
        {
            _load.hidden = NO;
        }
        self.page++;
        [self.atableView.mj_footer endRefreshing];
        [_atableView reloadData];
        
        if (arr.count < kPageSize) {
            [UIView animateWithDuration:0.3 animations:^{
                self.atableView.mj_footer.hidden = YES;// 没有数据说明是最后一页了，隐藏上拉加载
            }];
        } else {
            self.atableView.mj_footer.hidden = NO;
        }
        NSLog(@"%@", resultDict[@"message"]);
    } andFailure:^(NSError *error, NSString *errorMsg) {
        _load.hidden = NO;
        NSLog(@"商品搜索 %@", error);
    }];
}

- (void)addLefAndRightTableview
{
    _leftTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, GWIDTH / 2, GHEIGHT - 44 - 64 - 109) style:UITableViewStylePlain];
    _leftTableview.hidden = YES;
    _leftTableview.delegate = self;
    _leftTableview.dataSource = self;
    _leftTableview.rowHeight = 50;
    _leftTableview.tableFooterView = [UIView new];
    _leftTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_leftTableview registerClass:[HomeSearchLeftCell class] forCellReuseIdentifier:@"left"];
    [self.view addSubview:_leftTableview];
    
    _rightTableview = [[UITableView alloc] initWithFrame:CGRectMake(GWIDTH / 2, 44, GWIDTH / 2, GHEIGHT - 44 - 64 - 109) style:UITableViewStylePlain];
    _rightTableview.delegate = self;
    _rightTableview.dataSource = self;
    _rightTableview.hidden = YES;
    _rightTableview.backgroundColor = ColorFrom16(0xF7F7F7);
    _rightTableview.rowHeight = 50;
    _rightTableview.tableFooterView = [UIView new];
    _rightTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_rightTableview registerClass:[SearchRightCell class] forCellReuseIdentifier:@"right"];
    [self.view addSubview:_rightTableview];
    
    _bgView = [UIView new];
    _bgView.backgroundColor = ColorFrom16A(0x000000, 0.53);
    _bgView.hidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
    [_bgView addGestureRecognizer:tap];
    [self.view addSubview:_bgView];
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_leftTableview.mas_bottom);
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    _sortTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, GWIDTH, 150) style:UITableViewStylePlain];
    _sortTableview.delegate = self;
    _sortTableview.dataSource = self;
    _sortTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _sortTableview.hidden = YES;
    _sortTableview.rowHeight = 50;
    [_sortTableview registerClass:[HomeSearchLeftCell class] forCellReuseIdentifier:@"sort"];
    [self.view addSubview:_sortTableview];
    _aview = [UIView new];
    _aview.backgroundColor = ColorFrom16A(0x000000, 0.53);
    _aview.hidden = YES;
    
    UITapGestureRecognizer *tapSort = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapSort)];
    [_aview addGestureRecognizer:tapSort];
    
    [self.view addSubview:_aview];
    [_aview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_sortTableview.mas_bottom);
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    _nearbyLeftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, GWIDTH / 2, GHEIGHT - 44 - 64 - 109) style:UITableViewStylePlain];
    _nearbyLeftTableView.hidden = YES;
    _nearbyLeftTableView.delegate = self;
    _nearbyLeftTableView.dataSource = self;
    _nearbyLeftTableView.rowHeight = 50;
    _nearbyLeftTableView.tableFooterView = [UIView new];
    _nearbyLeftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_nearbyLeftTableView registerClass:[HomeSearchLeftCell class] forCellReuseIdentifier:@"nearbyleft"];
    [self.view addSubview:_nearbyLeftTableView];
    
    _nearbyRightTableView = [[UITableView alloc] initWithFrame:CGRectMake(GWIDTH / 2, 44, GWIDTH / 2, GHEIGHT - 44 - 64 - 109) style:UITableViewStylePlain];
    _nearbyRightTableView.delegate = self;
    _nearbyRightTableView.dataSource = self;
    _nearbyRightTableView.hidden = YES;
    _nearbyRightTableView.backgroundColor = ColorFrom16(0xF7F7F7);
    _nearbyRightTableView.rowHeight = 50;
    _nearbyRightTableView.tableFooterView = [UIView new];
    _nearbyRightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_nearbyRightTableView registerClass:[SearchRightCell class] forCellReuseIdentifier:@"nearbyright"];
    [self.view addSubview:_nearbyRightTableView];
    
    _bottomView = [UIView new];
    _bottomView.backgroundColor = ColorFrom16A(0x000000, 0.53);
    _bottomView.hidden = YES;
    
    UITapGestureRecognizer *tapBottom = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBottom)];
    [_bottomView addGestureRecognizer:tapBottom];
    
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nearbyLeftTableView.mas_bottom);
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
   }

- (void)handleTapBottom
{
    _nearbyRightTableView.hidden = YES;
    _nearbyLeftTableView.hidden = YES;
    [_nearbyBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _bottomView.hidden = YES;
    _nearbyBtn.selected = NO;
}

- (void)setNavigation
{
    
    _categoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_categoryBtn setImage:IMAGE(@"arrow_bottom") forState:0];
    [_categoryBtn setTitle:@"类别" forState:0];
    
    [_categoryBtn setImage:IMAGE(@"arrow_bottom") forState:UIWindowLevelNormal];
//    _categoryBtn.selected = YES;
    _categoryBtn.backgroundColor = ColorFrom16(0xffffff);
    [_categoryBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _categoryBtn.titleLabel.font = PFRFONT(14);
    [_categoryBtn addTarget:self action:@selector(actionCategory:) forControlEvents:UIControlEventTouchUpInside];
    [_categoryBtn setImage:IMAGE(@"arrow_up") forState:UIControlStateSelected];
    _categoryBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -60);
    _categoryBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -25, 0, 0);
    
    [self.view addSubview:_categoryBtn];
    [_categoryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.equalTo(self.view);
        make.width.equalTo(@(GWIDTH / 3));
        make.height.equalTo(@44);
    }];
    
    _nearbyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nearbyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nearbyBtn setTitle:@"附近" forState:0];
    [_nearbyBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _nearbyBtn.titleLabel.font = PFRFONT(14);
    _nearbyBtn.backgroundColor = ColorFrom16(0xffffff);
    [_nearbyBtn addTarget:self action:@selector(actionNearby:) forControlEvents:UIControlEventTouchUpInside];
    [_nearbyBtn setImage:IMAGE(@"arrow_bottom") forState:0];
    [_nearbyBtn setImage:IMAGE(@"arrow_up") forState:UIControlStateSelected];
    _nearbyBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -60);
    _nearbyBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -25, 0, 0);
    [self.view addSubview:_nearbyBtn];
    [_nearbyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_categoryBtn);
        make.left.equalTo(_categoryBtn.mas_right);
        make.width.equalTo(@(GWIDTH / 3));
        make.height.equalTo(@44);
    }];
    
    _sortBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sortBtn setTitle:@"排序" forState:0];
    [_sortBtn setImage:IMAGE(@"arrow_bottom") forState:0];
    [_sortBtn setImage:IMAGE(@"arrow_up") forState:UIControlStateSelected];
    [_sortBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    _sortBtn.titleLabel.font = PFRFONT(14);
    _sortBtn.backgroundColor = ColorFrom16(0xffffff);
    [_sortBtn addTarget:self action:@selector(actionSort:) forControlEvents:UIControlEventTouchUpInside];
    _sortBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -60);
    _sortBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -25, 0, 0);
    [self.view addSubview:_sortBtn];
    [_sortBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_categoryBtn);
        make.left.equalTo(_nearbyBtn.mas_right);
        make.width.equalTo(@(GWIDTH / 3));
        make.height.equalTo(@44);
    }];
    
    UIView *line = [UIView new];
    line.backgroundColor = COLOR_BACKGROUND;
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_categoryBtn.mas_bottom);
        make.left.and.right.equalTo(self.view);
        make.height.equalTo(@1);
    }];
    
    _atableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44 + 2, GWIDTH, GHEIGHT - 44 - 60) style:UITableViewStyleGrouped];
    _atableView.sectionHeaderHeight = 0.0001;
    self.atableView.contentInset = UIEdgeInsetsMake(-40, 0, 0, 0);

    _atableView.delegate = self;
    _atableView.dataSource = self;
    _atableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_atableView registerClass:[SearchFirstTableViewCell class] forCellReuseIdentifier:@"first"];
    [_atableView registerClass:[SearchListCell class] forCellReuseIdentifier:@"list"];
    [self.view addSubview:_atableView];
    _page = 1;
    _atableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(searchAppend)];
}

//上拉加载
- (void)searchAppend
{
    [self startGoodsNetwork];//搜索的商品的网络请求
}

#pragma mark - UITableViewDalegate

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(tableView == _atableView)
    {
        SearchModel *model = self.aArray[section];
        if(model.data.count > 2)
            return 54;
        else
            return 0;
    }
    else
        return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    SearchModel *model = self.aArray[section];
    if(model.data.count > 2)
    {
        UIView *aview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, 54)];
        aview.backgroundColor = ColorWhite;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 10, GWIDTH, 20);
        [btn setTitle:@"查看本店所有商品" forState:0];
        [btn setTitleColor:ColorFrom16(0xF8C450) forState:0];
        btn.titleLabel.font = PFRFONT(14);
        btn.titleLabel.textAlignment = 1;
        btn.tag = section;//把section 添加为tag
        [btn addTarget:self action:@selector(handleBtn:) forControlEvents:UIControlEventTouchUpInside];
        [aview addSubview:btn];
        UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, 44, GWIDTH, 10)];
        bg.backgroundColor = COLOR_BACKGROUND;
        [aview addSubview:bg];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 1, GWIDTH, 1)];
        line1.backgroundColor = COLOR_BACKGROUND;
        [aview addSubview:line1];
        return aview;
    }
    else
    {
        return [UIView new];
    }
}

//查看所有商品的响应方法
- (void)handleBtn:(UIButton *)sender
{
    //实现展开和收起
    if([[NSString stringWithFormat:@"%@", [self.boolArray objectAtIndex:sender.tag]] isEqualToString:@"1"])
    {
        [self.boolArray replaceObjectAtIndex:sender.tag withObject:@0];
    }
    else
    {
        [self.boolArray replaceObjectAtIndex:sender.tag withObject:@1];
    }
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:sender.tag];
    [_atableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];//点击完以后 刷新section
    NSLog(@"----%ld", sender.tag);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView == _atableView)
        return self.aArray.count;
    else
        return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _atableView)
    {
        if(indexPath.row == 0)
            return 113;
        else
            return 68;
    }
    else
        return 50;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == _atableView)
    {
        SearchModel *model = self.aArray[section];
        //        NSArray *arr = (NSArray *)[model.data objectAtIndex:section];
        if([self.boolArray[section] isEqualToNumber:@1])
            return  model.data.count + 1;
        else
            if(model.data.count == 0)
            {
                return 1;
            }
            else
                return 2;
        
    }
    else if (tableView == _leftTableview)
    {
        return _leftCategoryArry.count;
    }
    else if (tableView == _sortTableview)
    {
        return _sortAtrray.count;
    }
    else if(tableView == _rightTableview)
    {//右侧

        return _rightArray.count;
    }
    else if (tableView == _nearbyLeftTableView)
    {
        return _nearbyLeft.count;
    }
    else
    {
        return _nearbyRight.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _atableView)
    {
//        SearchGoodsBaseModel *model = self.baseArray[indexPath.section];
        SearchModel *model = self.aArray[indexPath.section];
        if(indexPath.row == 0)
        {
            //店铺
            SearchFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"first"];
            for(int i = 0; i < [model.base.store_grade integerValue]; i++)//动态加载星星
            {
               UIImageView *starImg = [[UIImageView alloc] initWithFrame:CGRectMake(111 + 20 * i, 72, 14, 14)];
                starImg.image = IMAGE(@"home_star");
                [cell addSubview:starImg];
            }
            [cell configViewWithModel:model];
            return cell;
        }
        else
        {
            //商品
            SearchModel *model = self.aArray[indexPath.section];
            DataModel *datamodel = model.data[indexPath.row - 1];
            SearchListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
            [cell configViewWithModel:datamodel];
            return cell;
        }
    }
    else if (tableView == _leftTableview)
    {//左侧tableview
        HomeSearchLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"left"];

            SearchRightModel *model = self.leftCategoryArry[indexPath.row];
            [cell configViewWithModel:model];
        
        
        if(_indexPth.row == indexPath.row)
        {
            cell.leftView.hidden = NO;
            cell.backgroundColor = ColorFrom16(0xf7f7f7);
        }
        else
        {
            cell.leftView.hidden = YES;
            cell.backgroundColor = ColorFrom16(0xffffff);
        }
        return cell;
    }
    else if (tableView == _sortTableview)
    {
        SortModel *model = self.sortAtrray[indexPath.row];
        HomeSearchLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sort"];
        cell.sortLabel.hidden = NO;
        cell.sortLabel.text = model.order_name;
        if(_indexPth.row == indexPath.row)
        {
            cell.leftView.hidden = NO;
            cell.backgroundColor = ColorFrom16(0xf7f7f7);
        }
        else
        {
            cell.leftView.hidden = YES;
            cell.backgroundColor = ColorFrom16(0xffffff);
        }
        return cell;
    }
    else if(tableView == _rightTableview)
    {
        
        //右侧tableview
        SearchRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"right"];
        cell.backgroundColor = ColorFrom16(0xF7F7F7);
        
        SearchRightModel *model = self.leftCategoryArry[_indexPth.row];
        [cell configViewWithModel:model index:indexPath.row];

        return cell;
    }
    else if (tableView == _nearbyLeftTableView)
    {
        HomeSearchLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearbyleft"];
        SearchNearbyModel *model = self.nearbyLeft[indexPath.row];
        [cell configNearbyithModel:model];
        
        if(_indexPth.row == indexPath.row)
        {
            cell.leftView.hidden = NO;
            cell.backgroundColor = ColorFrom16(0xf7f7f7);
        }
        else
        {
            cell.leftView.hidden = YES;
            cell.backgroundColor = ColorFrom16(0xffffff);
        }
        
        return cell;
    }
    else
    {
        SearchRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearbyright"];
        SearchNearbyModel *model = self.nearbyLeft[_indexPth.row];
        [cell configNearbyWithModel:model index:indexPath.row];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _leftTableview)
    {

        _indexPth = indexPath;
        SearchRightModel *model = self.leftCategoryArry[indexPath.row];
        _rightArray = (NSMutableArray *)model.data;
        [_rightTableview reloadData];
        [_leftTableview reloadData];
    }
    else if (tableView == _nearbyLeftTableView)
    {//附近左侧
        _indexPth = indexPath;
        SearchNearbyModel *model = self.nearbyLeft[indexPath.row];
        _nearbyRight = (NSMutableArray *)model.child_zone;
        [_nearbyLeftTableView reloadData];
        [_nearbyRightTableView reloadData];
    }
    else if(tableView == _nearbyRightTableView)
    {//附近右侧
        SearchNearbyModel *model = self.nearbyLeft[_indexPth.row];
        aRightModel *amodel = model.child_zone[indexPath.row];
        _lat = amodel.latitude;
        _lon = amodel.longitude;
        _page = 1;
        [self startGoodsNetwork];
        [self handleTapBottom];
    }
    else if(tableView == _sortTableview)
    {
        _indexPth = indexPath;
        
        SortModel *model = self.sortAtrray[indexPath.row];
        _sortKey = model.order;
        _page = 1;
        [self startGoodsNetwork];
        [_sortTableview reloadData];
        [self handleTapSort];
    }
    else if(tableView == _rightTableview)
    {//分类右侧
        SearchRightModel *model = self.leftCategoryArry[_indexPth.row];
        RightModel *rightModel = model.data[indexPath.row];
        _key = rightModel.id;
        _page = 1;
        [self startGoodsNetwork];
        [_atableView reloadData];
        [self handleTap];
    }
    else
    {
        if(indexPath.row != 0)
        {
            SearchModel *model = self.aArray[indexPath.section];
            DataModel *datamodel = model.data[indexPath.row - 1];
            NSString *lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"lat"];
            NSString *lon = [[NSUserDefaults standardUserDefaults] objectForKey:@"long"];
            [GW_webView handleWebView:[NSString stringWithFormat:@"%@/product/productDel.html?gid=%@&lat=%@&lon=%@", GW_Domain,datamodel.id, lat, lon] viewController:self titleName:@"首页" goodid:datamodel.id];
        }
    }
}


#pragma mark - 响应方法
- (void)TextfieldAction:(UITextField *)sender
{
    LastSearchViewController *searchVC = [LastSearchViewController new];
    searchVC.navigationItem.hidesBackButton = YES;
    searchVC.getKeyblock = ^(NSString *key) {
        
        _searchKey = key;
        NSLog(@"---- %@", key);
    };
    [self.navigationController pushViewController:searchVC animated:YES];
}

/***
 * 分类响应方法
 */
- (void)actionCategory:(UIButton *)sender
{
    [self.view bringSubviewToFront:_leftTableview];
    [self.view bringSubviewToFront:_rightTableview];
    [self.view bringSubviewToFront:_bgView];
    _indexPth = [NSIndexPath indexPathForRow:0 inSection:0];
    sender.selected = YES;
    _nearbyBtn.selected = NO;
    _sortBtn.selected = NO;
    [sender setTitleColor:ColorFrom16(0xFEDE6D) forState:0];
    [_sortBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [_nearbyBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [UIView animateWithDuration:0.5 animations:^{
        _bgView.hidden = NO;
        _leftTableview.hidden = NO;
        _rightTableview.hidden = NO;
        
        _nearbyRightTableView.hidden = YES;
        _nearbyLeftTableView.hidden = YES;
        _bottomView.hidden = YES;
        _aview.hidden = YES;
        _sortTableview.hidden = YES;
    }];
    [_leftTableview reloadData];
    [_rightTableview reloadData];
//    [_nearbyLeftTableView reloadData];
//    [_nearbyRightTableView reloadData];
   
}
/***
 * 附近响应方法
 */
- (void)actionNearby:(UIButton *)sender
{
    [self.view bringSubviewToFront:_nearbyLeftTableView];
    [self.view bringSubviewToFront:_nearbyRightTableView];
    [self.view bringSubviewToFront:_bottomView];
    _indexPth = [NSIndexPath indexPathForRow:0 inSection:0];
    sender.selected = YES;
    _categoryBtn.selected = NO;
    _sortBtn.selected = NO;
    [sender setTitleColor:ColorFrom16(0xFEDE6D) forState:0];
    [_categoryBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [_sortBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [UIView animateWithDuration:0.5 animations:^{
        _bgView.hidden = YES;
        _leftTableview.hidden = YES;
        _rightTableview.hidden = YES;
        
        _nearbyLeftTableView.hidden = NO;
        _nearbyRightTableView.hidden = NO;
        _bottomView.hidden = NO;
        _aview.hidden = YES;
        _sortTableview.hidden = YES;
    }];
    [_leftTableview reloadData];
    [_rightTableview reloadData];
    
    [_nearbyLeftTableView reloadData];
    [_nearbyRightTableView reloadData];

}

/***
 * 排序响应方法
 */
- (void)actionSort:(UIButton *)sender
{
    [self.view bringSubviewToFront:_sortTableview];
    [self.view bringSubviewToFront:_aview];
    
    sender.selected = YES;
    _categoryBtn.selected = NO;
    _nearbyBtn.selected = NO;
    [sender setTitleColor:ColorFrom16(0xFEDE6D) forState:0];
    [_categoryBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [_nearbyBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [UIView animateWithDuration:0.5 animations:^{
        _bgView.hidden = YES;
        _leftTableview.hidden = YES;
        _rightTableview.hidden = YES;
        _nearbyRightTableView.hidden = YES;
        _nearbyLeftTableView.hidden = YES;
        _bottomView.hidden = YES;
        _aview.hidden = NO;
        _sortTableview.hidden = NO;
    }];
}
/***
 * 轻拍手势响应方法
 */
- (void)handleTap
{
    [UIView animateWithDuration:0.5 animations:^{
        _bgView.hidden = YES;
        _leftTableview.hidden = YES;
        _rightTableview.hidden = YES;
        [self changeColor];
    }];
    _categoryBtn.selected = NO;
}

- (void)handleTapSort
{
    [UIView animateWithDuration:0.5 animations:^{
        _aview.hidden = YES;
        _sortTableview.hidden = YES;
        [self changeColor];
    }];
    _sortBtn.selected = NO;
}

- (void)changeColor
{
    [_categoryBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [_nearbyBtn setTitleColor:ColorFrom16(0x333333) forState:0];
    [_sortBtn setTitleColor:ColorFrom16(0x333333) forState:0];
}

- (void)handleBackBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    _page = 1;
    [[UINavigationBar appearance] setTranslucent:NO];//设置导航条透明
     [self startGoodsNetwork];//搜索的商品的网络请求
    if([GW_Tool isEmptyString:_searchKey])
    {
        _topLabel.text = @"      可输入店铺名、分类";
    }
    else
    {
        _topLabel.text = [NSString stringWithFormat:@"       %@", _searchKey];
    }
    [self.navigationController.navigationBar setShadowImage:nil];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //headerView
    if (scrollView == _atableView) {
        //去掉UItableview的section的headerview黏性
//        CGFloat sectionHeaderHeight = 54;
//        if (scrollView.contentOffset.y<=sectionHeaderHeight && scrollView.contentOffset.y>=0) {
//            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
//            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//        }
        self.atableView.contentInset = UIEdgeInsetsMake(-40, 0, 0, 0);

    }
    
//    footerView
//    if (scrollView == _tableView) {
//        //去掉UItableview的section的footerview黏性
//        CGFloat sectionFooterHeight = 54;
//        if (scrollView.contentOffset.y<=sectionFooterHeight && scrollView.contentOffset.y>=0) {
//            scrollView.contentInset = UIEdgeInsetsMake(0, 0, -sectionFooterHeight, 0);
//        } else if (scrollView.contentOffset.y>=sectionFooterHeight) {
//            scrollView.contentInset = UIEdgeInsetsMake(0, 0, -sectionFooterHeight, 0);
//        }
//    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [[UINavigationBar appearance] setTranslucent:NO];//设置导航条透明

    self.navigationController.navigationBar.barTintColor = ColorWhite;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
